<template>
  <!-- el-upload 相关的属性
action:可以指定提交图的服务器.如果需要自定义进行操作,那么action可以不指定具体的地址.给#
show-file-list
 -->
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :on-success="beforeAvatarUpload"
    :before-upload="upload"
  >
    <img v-if="value" :src="valid" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <el-progress v-if="showProgress" :percentage="percent" />

  </el-upload>
</template>

<script>
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKID74xhFbjvviMo21oOkApLgppdHmDSVVK2', // 身份识别ID
  SecretKey: 'ZutxpeJkz60jIcliV7W2XxA9wb8cyGTX' // 身份秘钥
})
export default {
  value: {
    type: String,
    default: ''
  },

  data() {
    return {
      showProgress: false,
      imageUrl: '',
      percent: 0
    }
  },
  methods: {
    upload(res) {
      if (res.file) {
        // 执行上传操作
        this.showProgress = true// 开始显示进度条
        // 执行上传操作
        cos.putObject({
          Bucket: 'wh84-1257017897', /* 存储桶 */
          Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // console.log(progressData, 'progressData')
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          console.log(err || data)
          // 上传成功之后
          if (data.statusCode === 200) {
            // console.log(data.Location, 'data.Location')
            this.imageUrl = `https://${data.Location}`
            this.$emit('input', `https://${data.Location}`)
          }
          this.showProgress = false// 上传完成关闭进度条
        })
      }
    },

    // handleAvatarSuccess(res, file) {
    //   this.imageUrl = URL.createObjectURL(file.raw)
    // },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

